package nirvana.core.mybatis.audit;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import nirvana.core.context.WebContext;
import nirvana.core.domains.entity.BaseAuditEntity;
import org.apache.commons.lang3.RandomUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;


import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * Audit interceptor / MBP interceptor implementation
 *
 * @author linkanyway
 * @version 1.0
 * @name MbpAuditInterceptor
 * @description TODO
 * @date 2021/09/20 13:12
 */
@Component
public class MbpAuditInterceptor implements MetaObjectHandler {
    /**
     * insertFill
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.getOriginalObject () instanceof BaseAuditEntity) {
           Long userId = WebContext.getCurrentUserId ();
            this.strictInsertFill (metaObject, "creator", Long.class, userId);
            this.strictInsertFill (metaObject, "createTime", LocalDateTime.class, LocalDateTime.now ());
            //prevent the column now allowed null value!!
            this.strictInsertFill (metaObject, "updater", Long.class, userId);
            this.strictInsertFill (metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now ());
        }
    }

    /**
     * updateFill
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        //check if the super class is BaseAuditEntity
        if (metaObject.getOriginalObject () instanceof BaseAuditEntity) {
            Long userId = WebContext.getCurrentUserId ();
            this.strictUpdateFill (metaObject, "updater", Long.class, userId);
            this.strictUpdateFill (metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now ());
        }
    }

    @Override
    public MetaObjectHandler strictFillStrategy(MetaObject metaObject, String fieldName, Supplier<?> fieldVal) {
        Object obj = fieldVal.get();
        if (Objects.nonNull(obj)) {
            metaObject.setValue(fieldName, obj);
        }
        return this;
    }
}
